package Day020_NIO_AIO.demo2_NIO2_AIO.Test4_AIO异步请求连接;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;

/**
 * @author zhangyan
 * @date 2020/5/13 11:03
 */
public class Client {
    public static void main(String[] args) throws Exception {
        //异步非阻塞客户端求情连接

        // 获取AsynchronousSocketChannel对象
        AsynchronousSocketChannel sc = AsynchronousSocketChannel.open();

        System.out.println(1);
        // 异步连接服务器
        sc.connect(new InetSocketAddress("127.0.0.1", 666), null, new CompletionHandler<Void, Object>() {
            @Override
            public void completed(Void result, Object attachment) {
                //连接成功
                System.out.println(3);

                //写数据
                //同步写/异步写
                // 创建ByteBuffer缓冲数组
                ByteBuffer b = ByteBuffer.allocate(1024);
                // 往缓冲数组中添加字节数据

                // 切换
                b.flip();

                // 写出数据
                sc.write(b, null, new CompletionHandler<Integer, Object>() {
                    @Override
                    public void completed(Integer result, Object attachment) {
                        System.out.println("...");
                    }

                    @Override
                    public void failed(Throwable exc, Object attachment) {

                    }
                });

            }

            @Override
            public void failed(Throwable exc, Object attachment) {
                //连接失败
                System.out.println(4);
            }
        });
        System.out.println(2);
        while (true){}
    }
}
